<?php
class Model{
	protected $db ;
	function __construct(){
		$this->db = Mysql::single()->getCon($this->dbconfig);
	}
	public function insert($data){
		$set = array();	
		foreach($data AS $k=>$v){
			$set = sprintf("%s='%s'",$k,$v);
		}
		$sql = sprintf("INSERT INTO %s SET %s",$this->tbl,implode(',',$set));
		if(mysql_query($sql,$this->db)){
			return mysql_insert_id($this->db);
		}
		return 0;
	}
	
	public function update($data,$where = null){
		$set = array();	
		foreach($data AS $k=>$v){
			$set = sprintf("%s='%s'",$k,$v);
		}
		$sql = sprintf("UPDATE %s SET %s %s",$this->tbl,implode(',',$set),($where ? " WHERE ".$where:""));
		if(mysql_query($sql,$this->db)){
			return mysql_affected_rows($this->db);
		}
		return 0;
	}
	public function getVar($sql){
		$row = $this->getRow($sql);
		if($row){
			foreach($row AS $val){
				return $val;
			}
		}
		return "";
	}
	public function del($where){
		$sql = srpintf("DELETE FROM %s WHERE 1=1 AND %s",$this->tbl,$where);
		if(mysql_query($sql,$this->db)){
			return mysql_affected_rows($this->db);
		}
		return 0;
	}
	public function getRow($sql){
		$list = $this->getResults($sql);
		if(count($list) > 0){
			return $list[0];
		}
		return null;
	}
	public function getResults($sql){
		if(!preg_match("/(select)\s+/i",$sql)){
			$sql = sprintf("SELECT * FROM %s WHERE %s",$this->tbl,$sql);
		}
		$rs = array();
		$list = mysql_query($sql,$this->db);
		if($list){
			while($row = mysql_fetch_assoc($list)){
				$rs[] = $row;
			}
		}
		return $rs;
	}
}
